//
//  NSTimer+Extension.m
//  ERPChargeAccount2
//
//  Created by 刘思麟 on 2018/6/1.
//  Copyright © 2018年 历山大亚. All rights reserved.
//

#import "NSTimer+Extension.h"
#import <objc/runtime.h>
#import <Aspects/Aspects.h>

@implementation NSTimer (Extension)

+ (void)load {
    Method m1 = class_getClassMethod([self class], @selector(timerWithTimeInterval:target:selector:userInfo:repeats:));
    Method m2 = class_getClassMethod([self class], @selector(sl_timerWithTimeInterval:target:selector:userInfo:repeats:));
    method_exchangeImplementations(m1, m2);
}

+ (NSTimer *)sl_timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo {
    NSTimer * timer = [self sl_timerWithTimeInterval:ti target:aTarget selector:aSelector userInfo:userInfo repeats:yesOrNo];
    __weak NSTimer * __weakTimer = timer;
    timer.target = aTarget;
    [aTarget aspect_hookSelector:aSelector withOptions:AspectPositionAfter usingBlock:^{
        if (__weakTimer.repeatCount >0 && __weakTimer.residualCount < 0) {
            [__weakTimer setFireDate:[NSDate distantFuture]];
        }
        __weakTimer.residualCount --;
    } error:nil];
    return timer;
}

- (void)remake {
    self.residualCount = self.repeatCount;
}

- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context {
    
}

- (void)setRepeatCount:(NSInteger)repeatCount {
    self.residualCount = repeatCount;
    objc_setAssociatedObject(self, "_repeatCount", @(repeatCount), OBJC_ASSOCIATION_ASSIGN);
}

- (NSInteger)repeatCount {
    return [objc_getAssociatedObject(self, "_repeatCount") integerValue];
}

- (void)setResidualCount:(NSInteger)residualCount {
    objc_setAssociatedObject(self, "_residualCount", @(residualCount), OBJC_ASSOCIATION_ASSIGN);
}

- (NSInteger)residualCount {
    return [objc_getAssociatedObject(self, "_residualCount") integerValue];
}

- (void)setTarget:(id)target {
    objc_setAssociatedObject(self, "sl_target", target, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)target {
    return objc_getAssociatedObject(self, "sl_target");
}

@end
